package com.ruoyi.advertisement.service.impl;

import java.util.List;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.advertisement.mapper.AdvertisementMaterialMapper;
import com.ruoyi.advertisement.domain.AdvertisementMaterial;
import com.ruoyi.advertisement.service.IAdvertisementMaterialService;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.common.core.utils.file.MimeTypeUtils;

/**
 * 广告素材Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Service
public class AdvertisementMaterialServiceImpl implements IAdvertisementMaterialService 
{
    @Autowired
    private AdvertisementMaterialMapper advertisementMaterialMapper;

    @Value("${file.upload.path:/uploads}")
    private String uploadPath;

    /**
     * 查询广告素材
     * 
     * @param materialId 广告素材主键
     * @return 广告素材
     */
    @Override
    public AdvertisementMaterial selectAdvertisementMaterialByMaterialId(Long materialId)
    {
        return advertisementMaterialMapper.selectAdvertisementMaterialByMaterialId(materialId);
    }

    /**
     * 查询广告素材列表
     * 
     * @param advertisementMaterial 广告素材
     * @return 广告素材
     */
    @Override
    public List<AdvertisementMaterial> selectAdvertisementMaterialList(AdvertisementMaterial advertisementMaterial)
    {
        return advertisementMaterialMapper.selectAdvertisementMaterialList(advertisementMaterial);
    }

    /**
     * 新增广告素材
     * 
     * @param advertisementMaterial 广告素材
     * @return 结果
     */
    @Override
    public int insertAdvertisementMaterial(AdvertisementMaterial advertisementMaterial)
    {
        advertisementMaterial.setCreateTime(DateUtils.getNowDate());
        advertisementMaterial.setCreateBy(SecurityUtils.getUsername());
        return advertisementMaterialMapper.insertAdvertisementMaterial(advertisementMaterial);
    }

    /**
     * 修改广告素材
     * 
     * @param advertisementMaterial 广告素材
     * @return 结果
     */
    @Override
    public int updateAdvertisementMaterial(AdvertisementMaterial advertisementMaterial)
    {
        advertisementMaterial.setUpdateTime(DateUtils.getNowDate());
        advertisementMaterial.setUpdateBy(SecurityUtils.getUsername());
        return advertisementMaterialMapper.updateAdvertisementMaterial(advertisementMaterial);
    }

    /**
     * 批量删除广告素材
     * 
     * @param materialIds 需要删除的广告素材主键
     * @return 结果
     */
    @Override
    public int deleteAdvertisementMaterialByMaterialIds(Long[] materialIds)
    {
        return advertisementMaterialMapper.deleteAdvertisementMaterialByMaterialIds(materialIds);
    }

    /**
     * 删除广告素材信息
     * 
     * @param materialId 广告素材主键
     * @return 结果
     */
    @Override
    public int deleteAdvertisementMaterialByMaterialId(Long materialId)
    {
        return advertisementMaterialMapper.deleteAdvertisementMaterialByMaterialId(materialId);
    }

    /**
     * 上传广告素材文件
     * 
     * @param file 上传的文件
     * @param materialType 素材类型
     * @return 素材信息
     */
    @Override
    public AdvertisementMaterial uploadMaterial(MultipartFile file, Integer materialType)
    {
        try {
            // 验证文件类型
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            if (materialType == 1) { // 图片
                assertAllowed(extension, MimeTypeUtils.IMAGE_EXTENSION);
            } else if (materialType == 2) { // 视频
                assertAllowed(extension, MimeTypeUtils.VIDEO_EXTENSION);
            }

            // 生成保存路径与文件名
            String datePath = DateUtils.datePath(); // yyyy/MM/dd
            String baseName = UUID.randomUUID().toString().replace("-", "");
            String fileName = baseName + "." + extension;
            Path dir = Paths.get(uploadPath, datePath);
            Files.createDirectories(dir);
            Path dest = dir.resolve(fileName);
            file.transferTo(dest.toFile());

            // 返回URL路径，前缀加/以适配网关静态映射策略
            String fileUrl = "/" + datePath + "/" + fileName;

            // 创建素材对象
            AdvertisementMaterial material = new AdvertisementMaterial();
            material.setMaterialName(file.getOriginalFilename());
            material.setMaterialType(materialType);
            material.setFileUrl(fileUrl);
            material.setFileSize(file.getSize());
            material.setStatus(1); // 默认启用
            material.setSortOrder(0);
            material.setViewCount(0L);
            material.setCreateTime(DateUtils.getNowDate());
            material.setCreateBy(SecurityUtils.getUsername());

            // 保存到数据库
            advertisementMaterialMapper.insertAdvertisementMaterial(material);

            return material;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败：" + e.getMessage());
        }
    }

    private void assertAllowed(String extension, String[] allowed)
    {
        boolean ok = false;
        for (String allow : allowed)
        {
            if (allow.equalsIgnoreCase(extension))
            {
                ok = true;
                break;
            }
        }
        if (!ok)
        {
            throw new RuntimeException("不支持的文件类型: " + extension);
        }
    }

    /**
     * 根据素材类型查询素材列表
     * 
     * @param materialType 素材类型
     * @return 素材列表
     */
    @Override
    public List<AdvertisementMaterial> selectMaterialsByType(Integer materialType)
    {
        return advertisementMaterialMapper.selectMaterialsByType(materialType);
    }

    /**
     * 根据状态查询素材列表
     * 
     * @param status 状态
     * @return 素材列表
     */
    @Override
    public List<AdvertisementMaterial> selectMaterialsByStatus(Integer status)
    {
        return advertisementMaterialMapper.selectMaterialsByStatus(status);
    }

    /**
     * 更新素材播放次数
     * 
     * @param materialId 素材ID
     * @return 结果
     */
    @Override
    public int incrementViewCount(Long materialId)
    {
        return advertisementMaterialMapper.incrementViewCount(materialId);
    }

    /**
     * 批量查询素材信息
     * 
     * @param materialIds 素材ID列表
     * @return 素材列表
     */
    @Override
    public List<AdvertisementMaterial> selectMaterialsByIds(List<Long> materialIds)
    {
        return advertisementMaterialMapper.selectMaterialsByIds(materialIds);
    }

    /**
     * 获取素材统计信息
     * 
     * @return 统计信息
     */
    @Override
    public MaterialStatistics getMaterialStatistics()
    {
        MaterialStatistics statistics = new MaterialStatistics();
        
        // 查询所有素材
        List<AdvertisementMaterial> allMaterials = advertisementMaterialMapper.selectAdvertisementMaterialList(new AdvertisementMaterial());
        
        int totalMaterials = allMaterials.size();
        int imageMaterials = 0;
        int videoMaterials = 0;
        int enabledMaterials = 0;
        long totalViewCount = 0;
        
        for (AdvertisementMaterial material : allMaterials) {
            if (material.getMaterialType() == 1) {
                imageMaterials++;
            } else if (material.getMaterialType() == 2) {
                videoMaterials++;
            }
            
            if (material.getStatus() == 1) {
                enabledMaterials++;
            }
            
            if (material.getViewCount() != null) {
                totalViewCount += material.getViewCount();
            }
        }
        
        statistics.setTotalMaterials(totalMaterials);
        statistics.setImageMaterials(imageMaterials);
        statistics.setVideoMaterials(videoMaterials);
        statistics.setEnabledMaterials(enabledMaterials);
        statistics.setTotalViewCount(totalViewCount);
        
        return statistics;
    }
} 